package com.css.fxfzxczh.modules.evaluationSummary.service.impl;

import com.css.fxfzxczh.constants.XczhConstants;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.entity.SamPoiData;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.repository.SamPoiDataRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.service.SamPoiDataService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.HouDamSta;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.SamPoiHouSur;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.repository.SamPoliHouSurRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.vo.ResultParamVo;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.entity.AdministrationAreaHousesDirectEconomicLosses;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.entity.DisasterAreasHousesDirectEconomicLosses;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.entity.HouseFailureRatioEntity;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.repository.HouseEconomicLossAssessRepository;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.service.HouseEconomicLossAssessService;
import com.css.fxfzxczh.modules.evaluationSummary.entity.*;
import com.css.fxfzxczh.modules.evaluationSummary.repository.EnterpriseDirectEconomyRepository;
import com.css.fxfzxczh.modules.evaluationSummary.service.EnterpriseDirectEconomyService;
import com.css.fxfzxczh.modules.evaluationSummary.vo.ParamsVo;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.entity.SurTaskManage;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.service.SurTaskManageService;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.entity.HouseCategoryArea;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.repository.HouseCategoryAreaRepository;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.entity.*;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.repository.*;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.strategy.StrategyService;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.vo.ResultVo;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.EarEveManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.UUIDGenerator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EnterpriseDirectEconomyServiceImpl implements EnterpriseDirectEconomyService {

    @Autowired
    SurTaskManageService surTaskManageService;
    @Autowired
    HouseEconomicLossAssessRepository houseEconomicLossAssessRepository;
    @Autowired
    EnterpriseDirectEconomyRepository enterpriseDirectEconomyRepository;
    @Autowired
    EnterpriseLossRepository enterpriseLossRepository;
    @Autowired
    ProLosInfoRepository proLosInfoRepository;
    @Autowired
    CasualtyInvestigationRepository casualtyInvestigationRepository;
    @Autowired
    PowerSysEquipmentRepository powerSysEquipmentRepository;
    @Autowired
    LosRepEscalationRepository losRepEscalationRepository;
    @Autowired
    ReportPublicFieldRepository reportPublicFieldRepository;
    @Autowired
    EarEveManageRepository earEveManageRepository;
    @Autowired
    SamPoliHouSurRepository samPoliHouSurRepository;
    @Autowired
    EarEveManageService earEveManageService;
    @Autowired
    RelicsHistoricSitesRepository relicsHistoricSitesRepository;
    @Autowired
    HouseCategoryAreaRepository houseCategoryAreaRepository;
    @Autowired
    HouseEconomicLossAssessService houseEconomicLossAssessService;
    @Autowired
    OtherLossRepository OtherLossRepository;
    @Autowired
    SamPoiDataService samPoiDataService;
    @Autowired
    SamPoiDataRepository samPoiDataRepository;
    @Resource
    WaterSysLossRepository waterSysLossRepository;


    @Override
    public void getEvaluationSubArea(ParamsVo paramsVo) {
        String type = paramsVo.getType();
        enterpriseDirectEconomyRepository.delteEnterpriseDirectEconomyByXsemId(paramsVo.getXsemId());//汇总/计算前先清空数据
        if(type.equals("0")){//企事业直接经济损失评估
            List<ResultVo> resultList = new ArrayList<>();
            //根据当前地震事件id    获取excel表导入的企业地震损失报表_固定资产部分 和 企业地震损失报表_流动资产部分的合计
            List<ResultVo> fixedAssetsTotal = enterpriseLossRepository.getFixedAssetsTotalByXsemId(paramsVo.getXsemId(),XczhConstants.ENTERPRISE_LOSS);//固定
            List<ResultVo> currentTotal = enterpriseLossRepository.getCurrentTotalByXsemId(paramsVo.getXsemId(),XczhConstants.ENTERPRISE_LOSS);
            if(fixedAssetsTotal.size()==0 && currentTotal.size()==0){
                throw new RuntimeException("企业地震损失数据为空，请在【地震灾害损失报表上报】模块中上传数据");
            }
            resultList.addAll(fixedAssetsTotal);
            resultList.addAll(currentTotal);
            // -----------------------按区县分组-------------------------------
            List<EnterpriseDirectEconomy> countyList = new ArrayList<>();
            Map<String, List<ResultVo>> countyGroup = new HashMap<>();
            for(ResultVo resultVo : resultList){
                String county = resultVo.getCounty();
                if (!countyGroup.containsKey(county)) {
                    countyGroup.put(county, new ArrayList<>());
                }
                countyGroup.get(county).add(resultVo);
            }
            BigDecimal total = BigDecimal.ZERO;//合计值
            for(String key : countyGroup.keySet()){
                List<ResultVo> resultVos = countyGroup.get(key);
                BigDecimal countyTotal = BigDecimal.ZERO;
                for(ResultVo resultVo : resultVos){
                    total = total.add(new BigDecimal(resultVo.getLoss()));
                    countyTotal = countyTotal.add(new BigDecimal(resultVo.getLoss()));
                }
                EnterpriseDirectEconomy enterpriseDirectEconomy = new EnterpriseDirectEconomy();
                enterpriseDirectEconomy.setId(UUIDGenerator.getUUID());
                enterpriseDirectEconomy.setXsemId(paramsVo.getXsemId());
                enterpriseDirectEconomy.setProvince(resultVos.get(0).getProvince());
                enterpriseDirectEconomy.setCity(resultVos.get(0).getCity());
                enterpriseDirectEconomy.setCounty(resultVos.get(0).getCounty());
                enterpriseDirectEconomy.setType(XczhConstants.REPORTED_LOSS);
                enterpriseDirectEconomy.setLoss(countyTotal);
                enterpriseDirectEconomy.setDelFlag("0");
                enterpriseDirectEconomy.setCreateUser(PlatformSessionContext.getUserID());
                enterpriseDirectEconomy.setCreateTime(new Date());
                enterpriseDirectEconomy.setCountType(XczhConstants.REPORTED_DATA);
                countyList.add(enterpriseDirectEconomy);
                enterpriseDirectEconomyRepository.saveEnterpriseDirectEconomy(enterpriseDirectEconomy);
            }
            //添加合计值
            EnterpriseDirectEconomy enterpriseDirectEconomy = new EnterpriseDirectEconomy();
            enterpriseDirectEconomy.setCounty("灾区");
            enterpriseDirectEconomy.setId(UUIDGenerator.getUUID());
            enterpriseDirectEconomy.setXsemId(paramsVo.getXsemId());
            enterpriseDirectEconomy.setType(XczhConstants.REPORTED_LOSS);
            enterpriseDirectEconomy.setLoss(total);
            enterpriseDirectEconomy.setDelFlag(YNEnum.N.toString());
            enterpriseDirectEconomy.setCreateUser(PlatformSessionContext.getUserID());
            enterpriseDirectEconomy.setCreateTime(new Date());
            enterpriseDirectEconomy.setCountType(XczhConstants.REPORTED_DATA);
            enterpriseDirectEconomyRepository.saveEnterpriseDirectEconomy(enterpriseDirectEconomy);
            countyList.add(enterpriseDirectEconomy);

            // -----------------------企业名称分组-----------------------
            /*List<EnterpriseDirectEconomy> enterpriseNameList = new ArrayList<>();
            Map<String, List<ResultVo>> enterpriseNameGroup = new HashMap<>();
            for(ResultVo resultVo : resultList){
                String enterpriseName = resultVo.getEnterpriseName();
                if (!enterpriseNameGroup.containsKey(enterpriseName)) {
                    enterpriseNameGroup.put(enterpriseName, new ArrayList<>());
                }
                enterpriseNameGroup.get(enterpriseName).add(resultVo);
            }
            BigDecimal total2 = BigDecimal.ZERO;//合计值
            for(String key : enterpriseNameGroup.keySet()){
                List<ResultVo> resultVos = enterpriseNameGroup.get(key);
                BigDecimal countyTotal = BigDecimal.ZERO;
                for(ResultVo resultVo : resultVos){
                    total2 = total2.add(new BigDecimal(resultVo.getLoss()));
                    countyTotal = countyTotal.add(new BigDecimal(resultVo.getLoss()));
                }
                EnterpriseDirectEconomy enterpriseDirectEconomy2 = new EnterpriseDirectEconomy();
                enterpriseDirectEconomy2.setId(UUIDGenerator.getUUID());
                enterpriseDirectEconomy2.setXsemId(paramsVo.getXsemId());
                *//*enterpriseDirectEconomy2.setProvince(resultVos.get(0).getProvince());
                enterpriseDirectEconomy2.setCity(resultVos.get(0).getCity());
                enterpriseDirectEconomy2.setCounty(resultVos.get(0).getCounty());*//*
                enterpriseDirectEconomy2.setEnterpriseName(key);
                enterpriseDirectEconomy2.setType("2");
                enterpriseDirectEconomy2.setLoss(countyTotal);
                enterpriseDirectEconomy2.setDelFlag("0");
                enterpriseDirectEconomy2.setCreateUser(PlatformSessionContext.getUserID());
                enterpriseDirectEconomy2.setCreateTime(new Date());
                enterpriseNameList.add(enterpriseDirectEconomy2);
                enterpriseDirectEconomyRepository.saveEnterpriseDirectEconomy(enterpriseDirectEconomy2);
            }
            //添加合计值
            EnterpriseDirectEconomy enterpriseDirectEconomy2 = new EnterpriseDirectEconomy();
            enterpriseDirectEconomy2.setEnterpriseName("灾区");
            enterpriseDirectEconomy2.setId(UUIDGenerator.getUUID());
            enterpriseDirectEconomy2.setXsemId(paramsVo.getXsemId());
            enterpriseDirectEconomy2.setType("2");
            if (!PlatformObjectUtils.isEmpty(total2)){
                enterpriseDirectEconomy2.setLoss(total2);
            }else{
                enterpriseDirectEconomy2.setLoss(BigDecimal.ZERO);
            }
            enterpriseDirectEconomy2.setDelFlag("0");
            enterpriseDirectEconomy2.setCreateUser(PlatformSessionContext.getUserID());
            enterpriseDirectEconomy2.setCreateTime(new Date());
            enterpriseDirectEconomyRepository.saveEnterpriseDirectEconomy(enterpriseDirectEconomy2);
            enterpriseNameList.add(enterpriseDirectEconomy2);
            map.put("huizong2",enterpriseNameList);*/
        }else if(type.equals("1")){//通过房屋直接经济损失估算
            //子区结果集合
            List<EnterpriseDirectEconomy> subZoneList=new ArrayList();
            //区划结果集合
            List<EnterpriseDirectEconomy> zoningList=new ArrayList();
            BigDecimal countCoefficient = paramsVo.getCountCoefficient();//计算系数
            //获取当前地震事件下所有数据齐全的评估子区
            List<SurTaskManage> evaluationSubArea = houseEconomicLossAssessService.getEvaluationSubArea(paramsVo.getXsemId());
            for(SurTaskManage surTaskManage : evaluationSubArea){
                String xstmId = surTaskManage.getXstmId();//评估子区id
                DisasterAreasHousesDirectEconomicLosses disasterAreasHouses = houseEconomicLossAssessRepository.getDisasterAreasHousesByXstmId(xstmId);
                EnterpriseDirectEconomy enterpriseDirectEconomy = new EnterpriseDirectEconomy();
                enterpriseDirectEconomy.setId(UUIDGenerator.getUUID());
                enterpriseDirectEconomy.setXsemId(paramsVo.getXsemId());
                enterpriseDirectEconomy.setType(XczhConstants.SUB_ZONE_LOSS);
                enterpriseDirectEconomy.setXstmId(xstmId);
                enterpriseDirectEconomy.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                enterpriseDirectEconomy.setCountCoefficient(countCoefficient);
                enterpriseDirectEconomy.setDelFlag(YNEnum.N.toString());
                enterpriseDirectEconomy.setCreateUser(PlatformSessionContext.getUserID());
                enterpriseDirectEconomy.setCreateTime(new Date());
                enterpriseDirectEconomy.setCountType(XczhConstants.HOUSE_ECONOMIC_LOSSES);
                if(!PlatformObjectUtils.isEmpty(disasterAreasHouses)){
                    BigDecimal loss = countCoefficient.multiply(disasterAreasHouses.getHousesLosses()).setScale(2, BigDecimal.ROUND_HALF_UP);//计算系数 * 房屋损失
                    enterpriseDirectEconomy.setLoss(loss);
                }
                subZoneList.add(enterpriseDirectEconomy);
            }
            List<AdministrationAreaHousesDirectEconomicLosses> administrationData = houseEconomicLossAssessRepository.getAdministrationData(paramsVo.getXsemId());
            for(AdministrationAreaHousesDirectEconomicLosses administration:administrationData){
                EnterpriseDirectEconomy enterpriseDirectEconomy = new EnterpriseDirectEconomy();
                enterpriseDirectEconomy.setXsemId(paramsVo.getXsemId());
                enterpriseDirectEconomy.setId(UUIDGenerator.getUUID());
                enterpriseDirectEconomy.setProvince(administration.getProvince());
                enterpriseDirectEconomy.setCity(administration.getCity());
                enterpriseDirectEconomy.setCounty(administration.getCounty());
                enterpriseDirectEconomy.setCountCoefficient(countCoefficient);
                enterpriseDirectEconomy.setLoss(countCoefficient.multiply(administration.getTotalLoss()).setScale(2, BigDecimal.ROUND_HALF_UP));
                enterpriseDirectEconomy.setCreateUser(PlatformSessionContext.getUserID());
                enterpriseDirectEconomy.setCreateTime(new Date());
                enterpriseDirectEconomy.setType(XczhConstants.ZONING_LOSS);
                enterpriseDirectEconomy.setDelFlag(YNEnum.N.toString());
                enterpriseDirectEconomy.setCountType(XczhConstants.HOUSE_ECONOMIC_LOSSES);
                zoningList.add(enterpriseDirectEconomy);
            }
            //保存以评估子区分组的损失结果
            enterpriseDirectEconomyRepository.batchSaveEnterprise(subZoneList);
            //保存以行政区划分组的损失结果
            enterpriseDirectEconomyRepository.batchSaveEnterprise(zoningList);
        }
    }

    @Override
    public Map<String, Object> getData(String xsemId) {
        Map<String, Object> map = new HashMap<>();
        List<EnterpriseDirectEconomy> list = enterpriseDirectEconomyRepository.getEnterpriseDirectEconomyByXsemId(xsemId);
        if (!PlatformObjectUtils.isEmpty(list)) {
            String type = list.get(0).getType();
            List<EnterpriseDirectEconomy> list1 = new ArrayList<>();
            List<EnterpriseDirectEconomy> list2 = new ArrayList<>();
            List<EnterpriseDirectEconomy> list3 = new ArrayList<>();
            for(EnterpriseDirectEconomy enterpriseDirectEconomy : list){
                String type1 = enterpriseDirectEconomy.getType();
                if (type1.equals("0")) {
                    list1.add(enterpriseDirectEconomy);
                } else if (type1.equals("2")) {
                    list2.add(enterpriseDirectEconomy);
                } else if (type1.equals("1")) {
                    list3.add(enterpriseDirectEconomy);
                }
            }
            map.put("type", type);
            map.put("huizong1", list1);
            map.put("huizong2", list2);
            map.put("jisuan", list3);
        }
        return map;
    }

    @Override
    public String checkData(String xsemId) {
        int count = enterpriseDirectEconomyRepository.getCountByType(xsemId);
        if(count != 0 ){
            return "是否要覆盖已计算的数据,重新计算";
        }
        return null;
    }

    @Override
    public String indoorOutdoorCheckData(String xsemId) {
        int count = enterpriseDirectEconomyRepository.getIndoorOutdoorCountByType(xsemId);
        if(count != 0 ){
            return "是否要覆盖已计算的数据,重新计算";
        }
        return null;
    }

    @Override
    @Transactional
    public void getIndoorOutdoorPropertyLosses(ParamsVo paramsVo) {
        String type = paramsVo.getType();
        //List<IndoorOutdoorPropertyLosses> list = new ArrayList<>();
        //清空当前地震事件下上报数据汇总结果和以评估子区分组汇总结果
        enterpriseDirectEconomyRepository.deleteIndoorOutdoorPropertyLossesByXsemId(paramsVo.getXsemId());
        if(type.equals("0")) {//室内外财产损失评估
            List<ProLosInfo> proLosInfoList = proLosInfoRepository.getProLosInfoByXsemId(paramsVo.getXsemId(),XczhConstants.PRO_LOS_INFO);
            if(proLosInfoList.size()==0){
                throw new RuntimeException("室内外财产损失数据为空，请在【地震灾害损失报表上报】模块中上传数据");
            }
            // 按区县分组
            Map<String, List<ProLosInfo>> countyGroup = new HashMap<>();
            for(ProLosInfo proLosInfo : proLosInfoList){
                String county = proLosInfo.getCounty();
                if (!countyGroup.containsKey(county)) {
                    countyGroup.put(county, new ArrayList<>());
                }
                countyGroup.get(county).add(proLosInfo);
            }
            BigDecimal indoorTotal = BigDecimal.ZERO;//室内合计值
            BigDecimal outdoorTotal = BigDecimal.ZERO;//室外合计值
            for(String key : countyGroup.keySet()){
                List<ProLosInfo> proLosInfos = countyGroup.get(key);
                BigDecimal countyIndoorTotal = BigDecimal.ZERO;
                BigDecimal countyOutdoorTotal = BigDecimal.ZERO;
                for(ProLosInfo proLosInfo : proLosInfos){
                    if(proLosInfo.getIndoorAndOutdoor().equals("室内")){
                        countyIndoorTotal = countyIndoorTotal.add(new BigDecimal(proLosInfo.getLossValue()));
                    }else if(proLosInfo.getIndoorAndOutdoor().equals("室外")){
                        countyOutdoorTotal = countyOutdoorTotal.add(new BigDecimal(proLosInfo.getLossValue()));
                    }
                }
                indoorTotal = indoorTotal.add(countyIndoorTotal);
                outdoorTotal = outdoorTotal.add(countyOutdoorTotal);
                IndoorOutdoorPropertyLosses  indoorOutdoorPropertyLosses = new IndoorOutdoorPropertyLosses();
                indoorOutdoorPropertyLosses.setId(UUIDGenerator.getUUID());
                indoorOutdoorPropertyLosses.setXsemId(paramsVo.getXsemId());
                indoorOutdoorPropertyLosses.setType(XczhConstants.REPORTED_LOSS);
                indoorOutdoorPropertyLosses.setProvince(proLosInfos.get(0).getProvince());
                indoorOutdoorPropertyLosses.setCity(proLosInfos.get(0).getCity());
                indoorOutdoorPropertyLosses.setCounty(proLosInfos.get(0).getCounty());
                indoorOutdoorPropertyLosses.setIndoorLoss(indoorTotal.divide(new BigDecimal("10000")));
                indoorOutdoorPropertyLosses.setOutdoorLoss(outdoorTotal.divide(new BigDecimal("10000")));
                indoorOutdoorPropertyLosses.setDelFlag(YNEnum.N.toString());
                indoorOutdoorPropertyLosses.setCreateUser(PlatformSessionContext.getUserID());
                indoorOutdoorPropertyLosses.setCreateTime(new Date());
                indoorOutdoorPropertyLosses.setCountType(XczhConstants.REPORTED_DATA);
                //list.add(indoorOutdoorPropertyLosses);
                enterpriseDirectEconomyRepository.saveIndoorOutdoorPropertyLosses(indoorOutdoorPropertyLosses);
            }
            //添加合计值
            IndoorOutdoorPropertyLosses indoorOutdoorPropertyLosses = new IndoorOutdoorPropertyLosses();
            indoorOutdoorPropertyLosses.setId(UUIDGenerator.getUUID());
            indoorOutdoorPropertyLosses.setXsemId(paramsVo.getXsemId());
            indoorOutdoorPropertyLosses.setCountType(XczhConstants.REPORTED_DATA);
            indoorOutdoorPropertyLosses.setCounty("灾区");
            indoorOutdoorPropertyLosses.setType(XczhConstants.REPORTED_LOSS);
            if (!PlatformObjectUtils.isEmpty(indoorTotal)){
                indoorOutdoorPropertyLosses.setIndoorLoss(indoorTotal.divide(new BigDecimal("10000")));
            }else{
                indoorOutdoorPropertyLosses.setIndoorLoss(BigDecimal.ZERO);
            }
            if (!PlatformObjectUtils.isEmpty(outdoorTotal)){
                indoorOutdoorPropertyLosses.setOutdoorLoss(outdoorTotal.divide(new BigDecimal("10000")));
            }else{
                indoorOutdoorPropertyLosses.setOutdoorLoss(BigDecimal.ZERO);
            }
            indoorOutdoorPropertyLosses.setDelFlag(YNEnum.N.toString());
            indoorOutdoorPropertyLosses.setCreateUser(PlatformSessionContext.getUserID());
            indoorOutdoorPropertyLosses.setCreateTime(new Date());
            enterpriseDirectEconomyRepository.saveIndoorOutdoorPropertyLosses(indoorOutdoorPropertyLosses);
            //list.add(indoorOutdoorPropertyLosses);
        }else if(type.equals("1")){//通过房屋直接经济损失估算
            BigDecimal indoorCountCoefficient = paramsVo.getIndoorCountCoefficient();//室内计算系数
            BigDecimal outdoorCountCoefficient = paramsVo.getOutdoorCountCoefficient();//室内计算系数
            //子区结果集合
            List<IndoorOutdoorPropertyLosses> subZoneList=new ArrayList();
            //区划结果集合
            List<IndoorOutdoorPropertyLosses> zoningList=new ArrayList();
            //获取当前地震事件下所有数据齐全的评估子区
            List<SurTaskManage> evaluationSubArea = houseEconomicLossAssessService.getEvaluationSubArea(paramsVo.getXsemId());
            for(SurTaskManage surTaskManage : evaluationSubArea){
                String xstmId = surTaskManage.getXstmId();//评估子区id
                DisasterAreasHousesDirectEconomicLosses disasterAreasHouses = houseEconomicLossAssessRepository.getDisasterAreasHousesByXstmId(xstmId);
                IndoorOutdoorPropertyLosses indoorOutdoorPropertyLosses = new IndoorOutdoorPropertyLosses();
                indoorOutdoorPropertyLosses.setId(UUIDGenerator.getUUID());
                indoorOutdoorPropertyLosses.setXsemId(paramsVo.getXsemId());
                indoorOutdoorPropertyLosses.setType(XczhConstants.SUB_ZONE_LOSS);
                indoorOutdoorPropertyLosses.setXstmId(xstmId);
                indoorOutdoorPropertyLosses.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                indoorOutdoorPropertyLosses.setIndoorCountCoefficient(indoorCountCoefficient);
                indoorOutdoorPropertyLosses.setOutdoorCountCoefficient(outdoorCountCoefficient);
                indoorOutdoorPropertyLosses.setDelFlag(YNEnum.N.toString());
                indoorOutdoorPropertyLosses.setCreateUser(PlatformSessionContext.getUserID());
                indoorOutdoorPropertyLosses.setCreateTime(new Date());
                indoorOutdoorPropertyLosses.setCountType(XczhConstants.HOUSE_ECONOMIC_LOSSES);
                if(!PlatformObjectUtils.isEmpty(disasterAreasHouses)){
                    //计算系数 * 房屋损失
                    BigDecimal indoorLoss = indoorCountCoefficient.multiply(disasterAreasHouses.getHousesLosses()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    indoorOutdoorPropertyLosses.setIndoorLoss(indoorLoss);
                    BigDecimal outdoorLoss = outdoorCountCoefficient.multiply(disasterAreasHouses.getHousesLosses()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    indoorOutdoorPropertyLosses.setOutdoorLoss(outdoorLoss);
                }
                subZoneList.add(indoorOutdoorPropertyLosses);
            }
            List<AdministrationAreaHousesDirectEconomicLosses> administrationData = houseEconomicLossAssessRepository.getAdministrationData(paramsVo.getXsemId());
            for(AdministrationAreaHousesDirectEconomicLosses administration:administrationData){
                IndoorOutdoorPropertyLosses indoorOutdoorPropertyLosses=new IndoorOutdoorPropertyLosses();
                indoorOutdoorPropertyLosses.setXsemId(paramsVo.getXsemId());
                indoorOutdoorPropertyLosses.setId(UUIDGenerator.getUUID());
                indoorOutdoorPropertyLosses.setProvince(administration.getProvince());
                indoorOutdoorPropertyLosses.setCity(administration.getCity());
                indoorOutdoorPropertyLosses.setCounty(administration.getCounty());
                indoorOutdoorPropertyLosses.setIndoorLoss(indoorCountCoefficient.multiply(administration.getTotalLoss()).setScale(2, BigDecimal.ROUND_HALF_UP));
                indoorOutdoorPropertyLosses.setOutdoorLoss(outdoorCountCoefficient.multiply(administration.getTotalLoss()).setScale(2, BigDecimal.ROUND_HALF_UP));
                indoorOutdoorPropertyLosses.setCreateUser(PlatformSessionContext.getUserID());
                indoorOutdoorPropertyLosses.setCreateTime(new Date());
                indoorOutdoorPropertyLosses.setType(XczhConstants.ZONING_LOSS);
                indoorOutdoorPropertyLosses.setDelFlag(YNEnum.N.toString());
                indoorOutdoorPropertyLosses.setCountType(XczhConstants.HOUSE_ECONOMIC_LOSSES);
                zoningList.add(indoorOutdoorPropertyLosses);
            }
            //保存以评估子区分组的损失结果
            enterpriseDirectEconomyRepository.batchSave(subZoneList);
            //保存以行政区划分组的损失结果
            enterpriseDirectEconomyRepository.batchSave(zoningList);
        }
    }

    @Override
    public List<IndoorOutdoorPropertyLosses> getIndoorOutdoorPropertyLossesData(String xsemId) {
        List<IndoorOutdoorPropertyLosses> list = enterpriseDirectEconomyRepository.getIndoorOutdoorPropertyLossesByXsemId(xsemId);
        return list;
    }

    @Override
    public Map<String, Object> getPersonnelInjuryData(String xsemId,int curPage,int pageSize) {
        List<PersonnelInjuryAssessment> personnelInjuryAssessmentList = enterpriseDirectEconomyRepository.getPersonnelInjuryData(xsemId);
        List<PersonnelInjuryAssessment> list = startPage(personnelInjuryAssessmentList, curPage, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("total", PlatformObjectUtils.isEmpty(personnelInjuryAssessmentList) ? 0 : personnelInjuryAssessmentList.size());
        map.put("rows", list);
        return map;
    }

    @Override
    public List<CasualtyInvestigation> getCauseDeaths(String xlrmId) {
        List<CasualtyInvestigation> casualtyInvestigationList = casualtyInvestigationRepository.findByXlrmId(xlrmId);
        return casualtyInvestigationList;
    }

    @Override
    @Transactional
    public void getPersonnelInjuryAssessment(String xsemId) {
        List<PersonnelInjuryAssessment> list = new ArrayList<>();
        enterpriseDirectEconomyRepository.deletePersonnelInjuryAssessmentByXsemId(xsemId);//汇总/计算前先清空数据
        List<CasualtyInvestigation> casualtyInvestigationList = casualtyInvestigationRepository.getCasualtyInvestigationByXsemId(xsemId,XczhConstants.CASUALTY_INVESTIGATION);
        if(casualtyInvestigationList.size()==0 || casualtyInvestigationList==null){
            throw new RuntimeException("人员伤亡数据为空，请在【地震灾害损失报表上报】模块中上传数据");
        }
        // 按村分组
        Map<String, List<CasualtyInvestigation>> villageGroup = new HashMap<>();
        for(CasualtyInvestigation casualtyInvestigation : casualtyInvestigationList){
            String village = casualtyInvestigation.getVillage();
            if (!villageGroup.containsKey(village)) {
                villageGroup.put(village, new ArrayList<>());
            }
            villageGroup.get(village).add(casualtyInvestigation);
        }
        BigDecimal deathCount = BigDecimal.ZERO;//死亡人数
        BigDecimal missingCount = BigDecimal.ZERO;//失踪人数
        BigDecimal badlyInjuredCount = BigDecimal.ZERO;//重伤人数
        BigDecimal minorInjuryCount = BigDecimal.ZERO;//轻伤人数
        String xlemId = ""; //总人数
        for(String key : villageGroup.keySet()) {
            BigDecimal totalPerson = BigDecimal.ZERO; //总人数
            List<CasualtyInvestigation> casualtyInvestigations = villageGroup.get(key);
            if (!PlatformObjectUtils.isEmpty(casualtyInvestigations)) {
                for (CasualtyInvestigation casualtyInvestigation : casualtyInvestigations) {
                    deathCount = deathCount.add(new BigDecimal(casualtyInvestigation.getDeath()));
                    missingCount = missingCount.add(new BigDecimal(casualtyInvestigation.getMissing()));
                    badlyInjuredCount = badlyInjuredCount.add(new BigDecimal(casualtyInvestigation.getBadlyInjured()));
                    minorInjuryCount = minorInjuryCount.add(new BigDecimal(casualtyInvestigation.getMinorInjury()));
                    xlemId=casualtyInvestigation.getXlrmId();
                }
                totalPerson = totalPerson.add(deathCount).add(missingCount).add(badlyInjuredCount).add(minorInjuryCount);
                PersonnelInjuryAssessment personnelInjuryAssessment = new PersonnelInjuryAssessment();
                personnelInjuryAssessment.setId(UUIDGenerator.getUUID());
                personnelInjuryAssessment.setXsemId(xsemId);
                personnelInjuryAssessment.setProvince(casualtyInvestigations.get(0).getProvince());
                personnelInjuryAssessment.setCity(casualtyInvestigations.get(0).getCity());
                personnelInjuryAssessment.setCounty(casualtyInvestigations.get(0).getCounty());
                personnelInjuryAssessment.setTownship(casualtyInvestigations.get(0).getTownship());
                personnelInjuryAssessment.setVillage(key);
                personnelInjuryAssessment.setSeismicIntensity(casualtyInvestigations.get(0).getSeismicIntensity());
                personnelInjuryAssessment.setDeath(deathCount);
                personnelInjuryAssessment.setMissing(missingCount);
                personnelInjuryAssessment.setBadlyInjured(badlyInjuredCount);
                personnelInjuryAssessment.setMinorInjury(minorInjuryCount);
                personnelInjuryAssessment.setTotalPerson(totalPerson);
                personnelInjuryAssessment.setDelFlag("0");
                personnelInjuryAssessment.setXlrmId(xlemId);
                personnelInjuryAssessment.setCreateUser(PlatformSessionContext.getUserID());
                personnelInjuryAssessment.setCreateTime(new Date());
                list.add(personnelInjuryAssessment);
                enterpriseDirectEconomyRepository.savePersonnelInjuryAssessment(personnelInjuryAssessment);
            }
        }
    }

    @Override
    public String lifelineSystemCheckData(String xsemId) {
        int count = enterpriseDirectEconomyRepository.getlifelineSystemCountByType(xsemId);
        if(count != 0 ){
            return "是否要覆盖已计算的数据,重新计算";
        }
        return null;
    }

    @Override
    @Transactional
    public void getLifelineSystemLoss(ParamsVo paramsVo) {
        String type = paramsVo.getType();
        enterpriseDirectEconomyRepository.deleteLifelineSystemLossByXsemId(paramsVo.getXsemId());//汇总/计算前先清空数据
        if (type.equals("0")) {//生命线系统直接经济损失评估
            //获取所有的省市区县

            //List<ResultVo> resultVos = new ArrayList<>();
            //List<IndoorOutdoorPropertyLossesZoning> entityList=new ArrayList();
            //List<ReportPublicField> countyReportPublicField = reportPublicFieldRepository.getReportPublicFieldGroupByCounty(paramsVo.getXsemId());

            List<LifelineSystemLoss> list = new ArrayList<>();
            List<AdministrationAreaHousesDirectEconomicLosses> administrationData = houseEconomicLossAssessRepository.getAdministrationData(paramsVo.getXsemId());

            BigDecimal total1 = BigDecimal.ZERO;
            for (AdministrationAreaHousesDirectEconomicLosses administration : administrationData) {
                String province = administration.getProvince();
                String city = administration.getCity();
                String county = administration.getCounty();
                String xsemId = paramsVo.getXsemId();
                paramsVo.setProvince(province);
                paramsVo.setCity(city);
                paramsVo.setCounty(county);
                /*LifelineSystemLoss lifelineSystemLoss = new LifelineSystemLoss();
                lifelineSystemLoss.setProvince(province);
                lifelineSystemLoss.setCity(city);
                lifelineSystemLoss.setCounty(county);
                lifelineSystemLoss.setXsemId(paramsVo.getXsemId());*/

                LifelineSystemLoss life = new LifelineSystemLoss();
                paramsVo.setReportType("0");
                BigDecimal dlTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//电力系统
                life.setLifelineType("0");
                if(PlatformObjectUtils.isEmpty(dlTotalLoss)){
                    dlTotalLoss=BigDecimal.ZERO;
                }
                life.setLoss(dlTotalLoss);
                list.add(saveLifelineSystemLoss(life, province, city, county, xsemId));

                LifelineSystemLoss life1 = new LifelineSystemLoss();
                paramsVo.setReportType("1");
                BigDecimal psTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//供排水系统
                life1.setLifelineType("1");
                if(PlatformObjectUtils.isEmpty(psTotalLoss)){
                    psTotalLoss=BigDecimal.ZERO;
                }
                life1.setLoss(psTotalLoss);
                list.add(saveLifelineSystemLoss(life1, province, city, county, xsemId));

                LifelineSystemLoss life2 = new LifelineSystemLoss();
                paramsVo.setReportType("2");
                BigDecimal gsTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//供气系统
                life2.setLifelineType("2");
                if(PlatformObjectUtils.isEmpty(gsTotalLoss)){
                    gsTotalLoss=BigDecimal.ZERO;
                }
                life2.setLoss(gsTotalLoss);
                list.add(saveLifelineSystemLoss(life2, province, city, county, xsemId));

                LifelineSystemLoss life3 = new LifelineSystemLoss();
                paramsVo.setReportType("3");
                BigDecimal grTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//供热系统
                life3.setLifelineType("3");
                if(PlatformObjectUtils.isEmpty(grTotalLoss)){
                    grTotalLoss=BigDecimal.ZERO;
                }
                life3.setLoss(grTotalLoss);
                list.add(saveLifelineSystemLoss(life3, province, city, county, xsemId));

                LifelineSystemLoss life4 = new LifelineSystemLoss();
                paramsVo.setReportType("4");
                BigDecimal jtTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//交通系统
                life4.setLifelineType("4");
                if(PlatformObjectUtils.isEmpty(jtTotalLoss)){
                    jtTotalLoss=BigDecimal.ZERO;
                }
                life4.setLoss(jtTotalLoss);
                list.add(saveLifelineSystemLoss(life4, province, city, county, xsemId));

                LifelineSystemLoss life5 = new LifelineSystemLoss();
                paramsVo.setReportType("5");
                BigDecimal csgTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//长输油 气管道
                life5.setLifelineType("5");
                if(PlatformObjectUtils.isEmpty(csgTotalLoss)){
                    csgTotalLoss=BigDecimal.ZERO;
                }
                life5.setLoss(csgTotalLoss);
                list.add(saveLifelineSystemLoss(life5, province, city, county, xsemId));

                LifelineSystemLoss life6 = new LifelineSystemLoss();
                paramsVo.setReportType("6");
                BigDecimal txTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//通信系统
                life6.setLifelineType("6");
                if(PlatformObjectUtils.isEmpty(txTotalLoss)){
                    txTotalLoss=BigDecimal.ZERO;
                }
                life6.setLoss(txTotalLoss);
                list.add(saveLifelineSystemLoss(life6, province, city, county, xsemId));

                LifelineSystemLoss life7 = new LifelineSystemLoss();
                paramsVo.setReportType("7");
                BigDecimal gbTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//广播电视系统
                life7.setLifelineType("7");
                if(PlatformObjectUtils.isEmpty(gbTotalLoss)){
                    gbTotalLoss=BigDecimal.ZERO;
                }
                life7.setLoss(gbTotalLoss);
                list.add(saveLifelineSystemLoss(life7, province, city, county, xsemId));

                LifelineSystemLoss life8 = new LifelineSystemLoss();
                paramsVo.setReportType("8");
                BigDecimal szTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//市政设施
                life8.setLifelineType("8");
                if(PlatformObjectUtils.isEmpty(szTotalLoss)){
                    szTotalLoss=BigDecimal.ZERO;
                }
                life8.setLoss(szTotalLoss);
                list.add(saveLifelineSystemLoss(life8, province, city, county, xsemId));

                // todo 铁路表中没有省市区县字段,不能用该维度汇总,待确认
                LifelineSystemLoss life9 = new LifelineSystemLoss();
                BigDecimal tlTotalLoss = BigDecimal.ZERO;
                paramsVo.setReportType("9");
                /*BigDecimal tlTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//铁路系统*/
                life9.setLifelineType("9");
                life9.setLoss(tlTotalLoss);
                list.add(saveLifelineSystemLoss(life9, province, city, county, xsemId));

                total1 = total1.add(dlTotalLoss).add(psTotalLoss).add(gsTotalLoss).add(grTotalLoss).add(jtTotalLoss).add(csgTotalLoss).add(txTotalLoss).add(gbTotalLoss).add(szTotalLoss).add(tlTotalLoss);

            }
            //添加合计值
            LifelineSystemLoss lifeline = new LifelineSystemLoss();
            lifeline.setLifelineType("灾区");
            lifeline.setLoss(total1);
            list.add(saveLifelineSystemLoss(lifeline, "", "", "合计值", paramsVo.getXsemId()));
            enterpriseDirectEconomyRepository.batchSaveLifeline(list);
            //获取所有的企业名称
            /*List<ResultVo> resultVos2 = new ArrayList<>();
            List<ReportPublicField> enterpriseNameReportPublicField = reportPublicFieldRepository.getReportPublicFieldGroupByEnterpriseName(paramsVo.getXsemId());
            BigDecimal total2 = BigDecimal.ZERO;
            ParamsVo paramsVo2 = new ParamsVo();
            paramsVo2.setXsemId(paramsVo.getXsemId());
            for(ReportPublicField reportPublicField : enterpriseNameReportPublicField){
                String enterpriseName = reportPublicField.getEnterpriseName();
                LifelineSystemLoss lifelineSystemLoss = new LifelineSystemLoss();
                paramsVo2.setEnterpriseName(enterpriseName);
                lifelineSystemLoss.setType("2");

                paramsVo2.setReportType("0");
                BigDecimal dlTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo);//电力系统
                lifelineSystemLoss.setLifelineType("0");
                lifelineSystemLoss.setLoss(dlTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);


                paramsVo2.setReportType("1");
                BigDecimal psTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//供排水系统
                lifelineSystemLoss.setLifelineType("1");
                lifelineSystemLoss.setLoss(psTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("2");
                BigDecimal gsTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//供气系统
                lifelineSystemLoss.setLifelineType("2");
                lifelineSystemLoss.setLoss(gsTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("3");
                BigDecimal grTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//供热系统
                lifelineSystemLoss.setLifelineType("3");
                lifelineSystemLoss.setLoss(grTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("4");
                BigDecimal jtTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//交通系统
                lifelineSystemLoss.setLifelineType("4");
                lifelineSystemLoss.setLoss(jtTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("5");
                BigDecimal csgTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//长输油 气管道
                lifelineSystemLoss.setLifelineType("5");
                lifelineSystemLoss.setLoss(csgTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("6");
                BigDecimal txTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//通信系统
                lifelineSystemLoss.setLifelineType("6");
                lifelineSystemLoss.setLoss(txTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("7");
                BigDecimal gbTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//广播电视系统
                lifelineSystemLoss.setLifelineType("7");
                lifelineSystemLoss.setLoss(gbTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("8");
                BigDecimal szTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//市政设施
                lifelineSystemLoss.setLifelineType("8");
                lifelineSystemLoss.setLoss(szTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                paramsVo2.setReportType("9");
                BigDecimal tlTotalLoss = losRepEscalationRepository.getTotalLoss(paramsVo2);//铁路系统
                lifelineSystemLoss.setLifelineType("9");
                lifelineSystemLoss.setLoss(tlTotalLoss);
                saveLifelineSystemLoss(lifelineSystemLoss);

                total2 = total2.add(dlTotalLoss).add(psTotalLoss).add(gsTotalLoss).add(grTotalLoss).add(jtTotalLoss).add(csgTotalLoss).add(txTotalLoss).add(gbTotalLoss).add(szTotalLoss).add(tlTotalLoss);

            }

            //添加合计值
            LifelineSystemLoss lifeline2 = new LifelineSystemLoss();
            lifeline2.setXsemId(paramsVo.getXsemId());
            lifeline2.setType("2");
            lifeline2.setEnterpriseName("合计值");
            lifeline2.setLifelineType("灾区");
            lifeline2.setLoss(total2);
            saveLifelineSystemLoss(lifeline2);*/

        } else if (type.equals("1")) {
            //子区结果集合
            List<LifelineSystemLoss> subZoneList = new ArrayList();
            //区划结果集合
            List<LifelineSystemLoss> zoningList = new ArrayList();
            BigDecimal countCoefficient = paramsVo.getCountCoefficient();//计算系数
            //获取当前地震事件下所有数据齐全的评估子区
            List<SurTaskManage> evaluationSubArea = houseEconomicLossAssessService.getEvaluationSubArea(paramsVo.getXsemId());
            for (SurTaskManage surTaskManage : evaluationSubArea) {
                String xstmId = surTaskManage.getXstmId();//评估子区id
                DisasterAreasHousesDirectEconomicLosses disasterAreasHouses = houseEconomicLossAssessRepository.getDisasterAreasHousesByXstmId(xstmId);
                LifelineSystemLoss lifelineSystemLoss = new LifelineSystemLoss();
                lifelineSystemLoss.setId(UUIDGenerator.getUUID());
                lifelineSystemLoss.setXsemId(paramsVo.getXsemId());
                lifelineSystemLoss.setType(XczhConstants.SUB_ZONE_LOSS);
                lifelineSystemLoss.setXstmId(xstmId);
                lifelineSystemLoss.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                lifelineSystemLoss.setCountCoefficient(countCoefficient);
                lifelineSystemLoss.setDelFlag("0");
                lifelineSystemLoss.setCreateUser(PlatformSessionContext.getUserID());
                lifelineSystemLoss.setCreateTime(new Date());
                lifelineSystemLoss.setCountType(XczhConstants.HOUSE_ECONOMIC_LOSSES);
                if (!PlatformObjectUtils.isEmpty(disasterAreasHouses)) {
                    BigDecimal indoorLoss = percentage(countCoefficient, disasterAreasHouses.getHousesLosses());//计算系数 * 房屋损失
                    lifelineSystemLoss.setLoss(indoorLoss);
                }
                subZoneList.add(lifelineSystemLoss);
            }
            List<AdministrationAreaHousesDirectEconomicLosses> administrationData = houseEconomicLossAssessRepository.getAdministrationData(paramsVo.getXsemId());
            for (AdministrationAreaHousesDirectEconomicLosses administration : administrationData) {
                LifelineSystemLoss lifelineSystemLoss = new LifelineSystemLoss();
                lifelineSystemLoss.setXsemId(paramsVo.getXsemId());
                lifelineSystemLoss.setId(UUIDGenerator.getUUID());
                lifelineSystemLoss.setProvince(administration.getProvince());
                lifelineSystemLoss.setCountCoefficient(countCoefficient);
                lifelineSystemLoss.setCity(administration.getCity());
                lifelineSystemLoss.setCounty(administration.getCounty());
                lifelineSystemLoss.setLoss(countCoefficient.multiply(administration.getTotalLoss()).setScale(2, BigDecimal.ROUND_HALF_UP));
                lifelineSystemLoss.setCreateUser(PlatformSessionContext.getUserID());
                lifelineSystemLoss.setCreateTime(new Date());
                lifelineSystemLoss.setType(XczhConstants.ZONING_LOSS);
                lifelineSystemLoss.setDelFlag(YNEnum.N.toString());
                lifelineSystemLoss.setCountType(XczhConstants.HOUSE_ECONOMIC_LOSSES);
                zoningList.add(lifelineSystemLoss);
            }
            enterpriseDirectEconomyRepository.batchSaveLifeline(subZoneList);
            enterpriseDirectEconomyRepository.batchSaveLifeline(zoningList);
        }
    }

    private LifelineSystemLoss saveLifelineSystemLoss (LifelineSystemLoss lifelineSystemLoss,String province,String city,String county,String xsemId){
        lifelineSystemLoss.setDelFlag("0");
        lifelineSystemLoss.setCreateUser(PlatformSessionContext.getUserID());
        lifelineSystemLoss.setCreateTime(new Date());
        lifelineSystemLoss.setCountType(XczhConstants.REPORTED_DATA);
        lifelineSystemLoss.setType(XczhConstants.REPORTED_LOSS);
        lifelineSystemLoss.setProvince(province);
        lifelineSystemLoss.setCity(city);
        lifelineSystemLoss.setCounty(county);
        lifelineSystemLoss.setXsemId(xsemId);
        lifelineSystemLoss.setId(UUIDGenerator.getUUID());
        return lifelineSystemLoss;
    }


    @Override
    public Map<String, Object> getLifelineSystemLossData(int curPage, int pageSize, String xsemId, String type) {
        Map<String, Object> map = new HashMap<>();
        List<LifelineSystemLoss> list = enterpriseDirectEconomyRepository.getLifelineSystemLossData(xsemId,type);
        if(type.equals("0")){
            List<LifelineSystemLoss> lifelineSystemLossList = lifelineSystemLossPage(list, curPage, pageSize);//分页查询
            map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
            map.put("rows", lifelineSystemLossList);
            map.put("type",type);
        }else if(type.equals("1") ||type.equals("2")){
            map.put("jisuan", list);
            map.put("type",type);
        }
        return map;
    }

    @Override
    public List<EarthquakeReliefCostAssessment> calculateEarthquakeReliefCostAssessment(String xsemId, String lossRatio1, String lossRatio2, String lossRatio3) {
        //计算时先进行删除
        enterpriseDirectEconomyRepository.deleteEarthquakeReliefCostAssessment(xsemId);
        //获取当前地震事件
        EarEveManage earEveManage = earEveManageRepository.findById(xsemId);
        double magnitude = Float.valueOf(earEveManage.getMagnitude());//震级
        BigDecimal f = BigDecimal.ZERO;
        if(magnitude<6){
            f = new BigDecimal(lossRatio1).divide(new BigDecimal("100"));
        }else if(6<=magnitude && magnitude<7){
            f = new BigDecimal(lossRatio2).divide(new BigDecimal("100"));
        }else if(magnitude>=7){
            f = new BigDecimal(lossRatio3).divide(new BigDecimal("100"));
        }
        //汇总的最终合计值
        BigDecimal total = enterpriseDirectEconomyRepository.getEconomicLossesSummaryTotal(xsemId);
        if(PlatformObjectUtils.isEmpty(total)){
            throw new RuntimeException("地震直接经济损失数据为空，请在【地震直接经济损失汇总】模块中汇总数据");
        }
        EarthquakeReliefCostAssessment earthquakeReliefCostAssessment = new EarthquakeReliefCostAssessment();
        earthquakeReliefCostAssessment.setId(UUIDGenerator.getUUID());
        earthquakeReliefCostAssessment.setXsemId(xsemId);
        earthquakeReliefCostAssessment.setDisasterAreaName(earEveManage.getEventName());
        earthquakeReliefCostAssessment.setCosts(total.multiply(f).setScale(2, RoundingMode.HALF_UP));
        earthquakeReliefCostAssessment.setDelFlag("0");
        earthquakeReliefCostAssessment.setCreateUser(PlatformSessionContext.getUserID());
        earthquakeReliefCostAssessment.setCreateTime(new Date());
        enterpriseDirectEconomyRepository.saveEarthquakeReliefCostAssessment(earthquakeReliefCostAssessment);
        List<EarthquakeReliefCostAssessment> list = new ArrayList<>();
        if(!PlatformObjectUtils.isEmpty(earthquakeReliefCostAssessment)){
            list.add(earthquakeReliefCostAssessment);
        }
        return list;
    }

    @Override
    public List<EarthquakeReliefCostAssessment> getEarthquakeReliefCostAssessment(String xsemId) {
        List<EarthquakeReliefCostAssessment> list = new ArrayList<>();
        EarthquakeReliefCostAssessment earthquakeReliefCostAssessment = enterpriseDirectEconomyRepository.getEarthquakeReliefCostAssessment(xsemId);
        if(!PlatformObjectUtils.isEmpty(earthquakeReliefCostAssessment)){
            list.add(earthquakeReliefCostAssessment);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ResettlementPopulationEvaluation> calculateResettlementPopulationEvaluation(String xsemId) {
        //计算时先进行删除
        enterpriseDirectEconomyRepository.deleteResettlementPopulationEvaluation(xsemId);
        //获取当前地震事件
        EarEveManage earEveManage = earEveManageRepository.findById(xsemId);
        List<String> xspdIdList = new ArrayList<>();
        //T=（c+d+e/2）/a×b-f
        //获取当前地震事件下所有数据齐全的评估子区
        List<SurTaskManage> evaluationSubArea = houseEconomicLossAssessService.getEvaluationSubArea(xsemId);
        //todo 暂时这样写，后续调查任务逻辑完善，需删除
//        List<SamPoiData> supSamPoiList=samPoiDataRepository.getSamListByType("0");

        for (SurTaskManage surTaskManage : evaluationSubArea) {
            List<SamPoiData> samList = samPoiDataService.getSamPoiListByXstmId(surTaskManage.getXstmId());



//            for(SamPoiData item:supSamPoiList){
//                Boolean boo=samPoiDataRepository.judPointPosition(surTaskManage.getXstmId(),item.getLongitude(),item.getLatitude());
//                if(boo){
//                    samList.add(item);
//                }
//            }


            xspdIdList.addAll(samList.stream()
                    .map(SamPoiData::getId)
                    .collect(Collectors.toList()));
        }
        ResultParamVo resultVo = samPoliHouSurRepository.getSamPoiHouSurCalculateByXsemId(xsemId, xspdIdList);
        BigDecimal totalArea = resultVo.getTotalArea();//所有【抽样点户数*户均房屋面积】之和
        BigDecimal population = resultVo.getSamplingPointPopulation();//总抽样人口
        BigDecimal households = resultVo.getSamplingPointHouseholds();//总抽样点户数

        BigDecimal a = BigDecimal.ZERO;
        a = totalArea;
        BigDecimal b = BigDecimal.ZERO;
        if (!(0 == population.compareTo(BigDecimal.ZERO))) {
            b = population.divide(households, 4, RoundingMode.HALF_UP);
        }
        BigDecimal c = BigDecimal.ZERO;
        BigDecimal d = BigDecimal.ZERO;
        BigDecimal e = BigDecimal.ZERO;
        BigDecimal f = BigDecimal.ZERO;
        for (SurTaskManage surTaskManage : evaluationSubArea) {
            String xstmId = surTaskManage.getXstmId();//评估子区id
            //建筑面积
            //每个评估子区下的每个结构类型下的建筑面积
            HouseCategoryArea typeTotalArea = houseCategoryAreaRepository.getHouseCategoryAreaByXstmId(xstmId, xsemId);
            //该评估子区的所有结构类型的毁坏的破坏比，
            List<HouseFailureRatioEntity> houseFailureRatioEntity = houseEconomicLossAssessRepository.getHouseFailureRatioByXstmId(xstmId);
            for (HouseFailureRatioEntity failureRatio : houseFailureRatioEntity) {
                String structureType = failureRatio.getStructureType();
                BigDecimal area = BigDecimal.ZERO;
                switch (structureType) {
                    case XczhConstants.ONE_TYPE:
                        area = area.add(typeTotalArea.getV1Area() != null ? typeTotalArea.getV1Area() : BigDecimal.ZERO);
                    case XczhConstants.TWO_TYPE:
                        area = area.add(typeTotalArea.getV2Area() != null ? typeTotalArea.getV2Area() : BigDecimal.ZERO);
                    case XczhConstants.THREE_ONE_TYPE:
                        area = area.add(typeTotalArea.getV3Area() != null ? typeTotalArea.getV3Area() : BigDecimal.ZERO);
                    case XczhConstants.THREE_TWO_TYPE:
                        area = area.add(typeTotalArea.getV4Area() != null ? typeTotalArea.getV4Area() : BigDecimal.ZERO);
                    case XczhConstants.FOUR_TYPE:
                        area = area.add(typeTotalArea.getV5Area() != null ? typeTotalArea.getV5Area() : BigDecimal.ZERO);
                    case XczhConstants.FIVE_ONE_TYPE:
                        area = area.add(typeTotalArea.getV6Area() != null ? typeTotalArea.getV6Area() : BigDecimal.ZERO);
                    case XczhConstants.FIVE_TWO_TYPE:
                        area = area.add(typeTotalArea.getV7Area() != null ? typeTotalArea.getV7Area() : BigDecimal.ZERO);
                    case XczhConstants.FIVE_THREE_TYPE:
                        area = area.add(typeTotalArea.getV8Area() != null ? typeTotalArea.getV8Area() : BigDecimal.ZERO);
                    case XczhConstants.SIX_TYPE:
                        area = area.add(typeTotalArea.getV9Area() != null ? typeTotalArea.getV9Area() : BigDecimal.ZERO);
                    case XczhConstants.SEVEN_TYPE:
                        area = area.add(typeTotalArea.getV10Area() != null ? typeTotalArea.getV10Area() : BigDecimal.ZERO);
                    default:
                        // Handle unrecognized structure type
                        break;
                }
                //计算c
                BigDecimal destroyRatio = new BigDecimal(failureRatio.getDestroyRatio());
                if(!(0 == destroyRatio.compareTo(BigDecimal.ZERO))){
                    BigDecimal cResult = area.multiply(destroyRatio);
                    c = c.add(cResult);
                }else{
                    c = c.add(BigDecimal.ZERO);
                }

                //计算d
                BigDecimal seriousRatio = new BigDecimal(failureRatio.getSeriousRatio());
                if(!(0 == seriousRatio.compareTo(BigDecimal.ZERO))){
                    BigDecimal dResult = area.multiply(seriousRatio);
                    d = d.add(dResult);
                }else{
                    d = d.add(BigDecimal.ZERO);
                }


                //计算e
                BigDecimal moderateRatio = new BigDecimal(failureRatio.getModerateRatio());
                if(!(0 == moderateRatio.compareTo(BigDecimal.ZERO))){
                    BigDecimal eResult = area.multiply(moderateRatio);
                    e = e.add(eResult);
                }else{
                    e = e.add(BigDecimal.ZERO);
                }

            }
        }
        List<CasualtyInvestigation> casualtyInvestigationList = casualtyInvestigationRepository.getCasualtyInvestigationByXsemId(xsemId, XczhConstants.CASUALTY_INVESTIGATION);
        f = casualtyInvestigationList.stream()
                .map(CasualtyInvestigation -> new BigDecimal(CasualtyInvestigation.getDeath()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        /*//计算f
        if(!PlatformObjectUtils.isEmpty(samPoiHouSur.getDeathToll())){
            f = new BigDecimal(samPoiHouSur.getDeathToll());//死亡人数
        }*/

        // float v = (c + d + e / 2) / a * b - f;
        BigDecimal v = BigDecimal.ZERO;//需安置人数
        BigDecimal num1 = c.add(d).add(e.divide(BigDecimal.valueOf(2)));
        if (!(0 == a.compareTo(BigDecimal.ZERO))) {// 避免除以零错误
            BigDecimal result = num1.divide(a, 2, RoundingMode.HALF_UP).multiply(b).subtract(f); // 进行四舍五入并保留2位小数
            v = result.setScale(0, RoundingMode.HALF_UP); // 将结果进行四舍五入并保留2位小数// 避免除以零错误
        }
        ResettlementPopulationEvaluation resettlementPopulationEvaluation = new ResettlementPopulationEvaluation();
        resettlementPopulationEvaluation.setId(UUIDGenerator.getUUID());
        resettlementPopulationEvaluation.setXsemId(xsemId);
        resettlementPopulationEvaluation.setDisasterAreaName(earEveManage.getEventName());
        resettlementPopulationEvaluation.setAValue(a.setScale(2, RoundingMode.HALF_UP));
        resettlementPopulationEvaluation.setBValue(b.setScale(2, RoundingMode.HALF_UP));
        resettlementPopulationEvaluation.setCValue(c.setScale(2, RoundingMode.HALF_UP));
        resettlementPopulationEvaluation.setDValue(d.setScale(2, RoundingMode.HALF_UP));
        resettlementPopulationEvaluation.setEValue(e.setScale(2, RoundingMode.HALF_UP));
        resettlementPopulationEvaluation.setFValue(f.setScale(2, RoundingMode.HALF_UP));
        resettlementPopulationEvaluation.setResettlePeopleNumber(v.compareTo(BigDecimal.ZERO) <=0 ? BigDecimal.ZERO:v);
        resettlementPopulationEvaluation.setDelFlag("0");
        resettlementPopulationEvaluation.setCreateUser(PlatformSessionContext.getUserID());
        resettlementPopulationEvaluation.setCreateTime(new Date());
        enterpriseDirectEconomyRepository.saveResettlementPopulationEvaluation(resettlementPopulationEvaluation);
        List<ResettlementPopulationEvaluation> list = new ArrayList<>();
        if (!PlatformObjectUtils.isEmpty(resettlementPopulationEvaluation)) {
            list.add(resettlementPopulationEvaluation);
        }
        return list;
    }

    @Override
    public List<ResettlementPopulationEvaluation> getResettlementPopulationEvaluation(String xsemId) {
        ResettlementPopulationEvaluation resettlementPopulationEvaluation = enterpriseDirectEconomyRepository.getResettlementPopulationEvaluation(xsemId);
        List<ResettlementPopulationEvaluation> list = new ArrayList<>();
        if(!PlatformObjectUtils.isEmpty(resettlementPopulationEvaluation)){
            list.add(resettlementPopulationEvaluation);
        }
        return list;
    }

    @Override
    public String economicLossesSummaryTips() {
        StringBuilder stringBuilder = new StringBuilder("");
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        String xsemId = currentEvent.getXsemId();
        //获取当前地震事件下,所有省市县
        List<AdministrationAreaHousesDirectEconomicLosses> administrationData = houseEconomicLossAssessRepository.getAdministrationData(xsemId);
        if (CollectionUtils.isEmpty(administrationData)){
            stringBuilder.append("房屋直接经济损失、");
        }
        List<LifelineSystemLoss> lifelineSystemLossList = enterpriseDirectEconomyRepository.getLifelineSystemLossData(xsemId, XczhConstants.REPORTED_LOSS);
        if (CollectionUtils.isEmpty(lifelineSystemLossList)){
            stringBuilder.append("生命线系统直接经济损失、");
        }
        List<EnterpriseDirectEconomy> enterpriseDirectEconomy = enterpriseDirectEconomyRepository.getEnterpriseDirectEconomy(xsemId, XczhConstants.ZONING_LOSS);
        if (CollectionUtils.isEmpty(enterpriseDirectEconomy)){
            stringBuilder.append("企业直接经济损失、");
        }
        List<WaterSysEquipment> waterSysLossData = waterSysLossRepository.getWaterSysLossData(xsemId, XczhConstants.WATER_SYS_LOSS_EQUIPMENT);
        if (CollectionUtils.isEmpty(waterSysLossData)){
            stringBuilder.append("水利财产损失、");
        }
        List<ResultVo> architectureTotal = relicsHistoricSitesRepository.getArchitectureTotalLoss(xsemId, "", "", "", XczhConstants.RELICS_HISTORIC_SITES);
        List<ResultVo> currentAssetsTotal = relicsHistoricSitesRepository.getCurrentAssetsTotalLoss(xsemId, "", "", "", XczhConstants.RELICS_HISTORIC_SITES);
        if (CollectionUtils.isEmpty(architectureTotal) && CollectionUtils.isEmpty(currentAssetsTotal))  {
            stringBuilder.append("文物古建财产损失、");
        }

        List<OtherLoss> otherLoss = OtherLossRepository.getOtherLoss(xsemId, XczhConstants.OTHER_LOSS);
        if (CollectionUtils.isEmpty(otherLoss))  {
            stringBuilder.append("其他财产损失、");
        }
        //水利、文物古建、其他
        List<IndoorOutdoorPropertyLosses> indoorOutdoorPropertyLossesByXsemId = enterpriseDirectEconomyRepository.getIndoorOutdoorPropertyLossesByXsemId(xsemId);
        if (CollectionUtils.isEmpty(indoorOutdoorPropertyLossesByXsemId)){
            stringBuilder.append("室内外财产损失、");
        }
        if (stringBuilder.length()>0){
            StringBuilder str= new StringBuilder("当前地震事件下：");
            str.append(stringBuilder);
            str.append("尚未计算完成，是否继续汇总？");
            return str.toString();
        }
        return "";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getEconomicLossesSummary() {
        economicLossesSummaryTips();
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        String xsemId = currentEvent.getXsemId();

        //删除已汇总的数据,再重新计算 todo  真正测试时需要放开
        enterpriseDirectEconomyRepository.deleteEconomicLossesSummary(xsemId);
        //房屋小计
        BigDecimal ruralHouseSubtotal = BigDecimal.ZERO;
        BigDecimal ruralSharedSubtotal = BigDecimal.ZERO;
        BigDecimal cityHouseSubtotal = BigDecimal.ZERO;
        BigDecimal citySharedSubtotal = BigDecimal.ZERO;
        BigDecimal governmentOfficeSubtotal = BigDecimal.ZERO;
        BigDecimal educationSystemSubtotal = BigDecimal.ZERO;//教育系统
        BigDecimal healthSystemSubtotal = BigDecimal.ZERO;//医疗系统
        BigDecimal otherUsageSubtotal = BigDecimal.ZERO;//其他用途

        //生命线小计
        BigDecimal dlSubtotal = BigDecimal.ZERO;
        BigDecimal gpsSubtotal = BigDecimal.ZERO;
        BigDecimal gqSubtotal = BigDecimal.ZERO;
        BigDecimal grSubtotal = BigDecimal.ZERO;
        BigDecimal jtSubtotal = BigDecimal.ZERO;
        BigDecimal csyqgSubtotal = BigDecimal.ZERO;
        BigDecimal txSubtotal = BigDecimal.ZERO;
        BigDecimal gbdsSubtotal = BigDecimal.ZERO;
        BigDecimal szssSubtotal = BigDecimal.ZERO;
        BigDecimal tlSubtotal = BigDecimal.ZERO;
        //企业小计
        BigDecimal qySubtotal = BigDecimal.ZERO;
        //水利小计
        BigDecimal slSubtotal = BigDecimal.ZERO;
        //文物古建小计
        BigDecimal wwgjSubtotal = BigDecimal.ZERO;
        //其他小计
        BigDecimal qtSubtotal = BigDecimal.ZERO;
        //室内外财产小计
        BigDecimal snSubtotal = BigDecimal.ZERO;
        //室外财产小计
        BigDecimal swSubtotal = BigDecimal.ZERO;
        //合计小计
        BigDecimal totalSubtotal = BigDecimal.ZERO;
        //获取当前地震事件下,所有省市县
        List<AdministrationAreaHousesDirectEconomicLosses> administrationData = houseEconomicLossAssessRepository.getAdministrationData(xsemId);
        if (administrationData.size() > 0) {
            for (AdministrationAreaHousesDirectEconomicLosses administration : administrationData) {
                String province = administration.getProvince();
                String city = administration.getCity();
                String county = administration.getCounty();

                EconomicLossesSummary economicLossesSummary = new EconomicLossesSummary();
                economicLossesSummary.setId(UUIDGenerator.getUUID());
                economicLossesSummary.setXsemId(xsemId);
                economicLossesSummary.setEventName(currentEvent.getEventName());
                economicLossesSummary.setEventTime(currentEvent.getEventTime());
                economicLossesSummary.setProvince(province);
                economicLossesSummary.setCity(city);
                economicLossesSummary.setCounty(county);
                BigDecimal total = BigDecimal.ZERO;
                //获取房屋相关数据

                BigDecimal ruralHouse = administration.getRuralHouse();
                BigDecimal ruralShared = administration.getRuralShared();
                BigDecimal cityHouse = administration.getCityHouse();
                BigDecimal cityShared = administration.getCityShared();
                BigDecimal governmentOffice = administration.getGovernmentOffice();
                BigDecimal educationSystem = administration.getEducationSystem();
                BigDecimal healthSystem = administration.getHealthSystem();
                BigDecimal otherUsage = administration.getOtherUsage();
                economicLossesSummary.setRuralResidential(ruralHouse);//农村住宅
                economicLossesSummary.setRuralPublic(ruralShared);//农村公共
                economicLossesSummary.setUrbanResidential(cityHouse);//城市住宅
                economicLossesSummary.setUrbanPublic(cityShared);//城市公共
                economicLossesSummary.setGovernmentOffice(governmentOffice);//政府办公
                economicLossesSummary.setEducationSystem(educationSystem);//教育系统
                economicLossesSummary.setHealthcareSystem(healthSystem);//卫生系统
                economicLossesSummary.setOtherUsage(otherUsage);//其他用途
                //合计相关计算
                total = total.add(ruralHouse).add(ruralShared).add(cityHouse).add(cityShared).add(governmentOffice).add(educationSystem).add(healthSystem).add(otherUsage);
                //计算小计
                ruralHouseSubtotal = ruralHouseSubtotal.add(ruralHouse);
                ruralSharedSubtotal = ruralSharedSubtotal.add(ruralShared);
                cityHouseSubtotal = cityHouseSubtotal.add(cityHouse);
                citySharedSubtotal = citySharedSubtotal.add(cityShared);
                governmentOfficeSubtotal = governmentOfficeSubtotal.add(governmentOffice);
                educationSystemSubtotal = educationSystemSubtotal.add(educationSystem);
                healthSystemSubtotal = healthSystemSubtotal.add(healthSystem);
                otherUsageSubtotal = otherUsageSubtotal.add(otherUsage);

                //获取生命线相关数据
                List<LifelineSystemLoss> lifelineSystemLossList = enterpriseDirectEconomyRepository.getLifelineSystemLossByXsemIdAndCounty(xsemId, province, city, county, XczhConstants.REPORTED_LOSS);
                BigDecimal dl = BigDecimal.ZERO;
                BigDecimal gps = BigDecimal.ZERO;
                BigDecimal gq = BigDecimal.ZERO;
                BigDecimal gr = BigDecimal.ZERO;
                BigDecimal jt = BigDecimal.ZERO;
                BigDecimal csyqg = BigDecimal.ZERO;
                BigDecimal tx = BigDecimal.ZERO;
                BigDecimal gbds = BigDecimal.ZERO;
                BigDecimal szss = BigDecimal.ZERO;
                BigDecimal tl = BigDecimal.ZERO;
                for (LifelineSystemLoss lifelineSystemLoss : lifelineSystemLossList) {
                    String lifelineTypeType = lifelineSystemLoss.getLifelineType();
                    if (XczhConstants.POWER_SYS_EQUIPMENT.equals(lifelineTypeType)) {
                        dl = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.DRA_SYS_LOSS.equals(lifelineTypeType)) {
                        gps = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.SUP_SYS_LOSS.equals(lifelineTypeType)) {
                        gq = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.HEA_SYS_LOSS.equals(lifelineTypeType)) {
                        gr = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.TRA_SYS_LOSS.equals(lifelineTypeType)) {
                        jt = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.LON_OIL_PIP_LOSS.equals(lifelineTypeType)) {
                        csyqg = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.COM_SYS_LOSS.equals(lifelineTypeType)) {
                        tx = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.RAD_TEL_SYS_LOSS.equals(lifelineTypeType)) {
                        gbds = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.MUNICIPAL_FACILITIES.equals(lifelineTypeType)) {
                        szss = lifelineSystemLoss.getLoss();
                    } else if (XczhConstants.RAILWAY_SYS_EQUIPMENT.equals(lifelineTypeType)) {
                        tl = lifelineSystemLoss.getLoss();
                    }
                }
                economicLossesSummary.setElectricity(dl);//电力
                economicLossesSummary.setWaterSupplyAndDrainage(gps);//供排水
                economicLossesSummary.setGasSupply(gq);//供气
                economicLossesSummary.setHeatingSupply(gr);//供热
                economicLossesSummary.setTraffic(jt);//交通
                economicLossesSummary.setOilAndGasPipelines(csyqg);//长输油、气管
                economicLossesSummary.setCommunication(tx);//通信
                economicLossesSummary.setBroadcastingAndTelevision(gbds);//广播电视
                economicLossesSummary.setMunicipalFacilities(szss);//市政设施
                economicLossesSummary.setRailway(tl);//铁路

                //合计相关计算
                total = total.add(dl).add(gps).add(gq).add(gr).add(jt).add(csyqg).add(tx).add(gbds).add(szss).add(tl);
                //计算小计
                dlSubtotal = dlSubtotal.add(dl);
                gpsSubtotal = gpsSubtotal.add(gps);
                gqSubtotal = gqSubtotal.add(gq);
                grSubtotal = grSubtotal.add(gr);
                jtSubtotal = jtSubtotal.add(jt);
                csyqgSubtotal = csyqgSubtotal.add(csyqg);
                txSubtotal = txSubtotal.add(tx);
                gbdsSubtotal = gbdsSubtotal.add(gbds);
                szssSubtotal = szssSubtotal.add(szss);
                tlSubtotal = tlSubtotal.add(tl);

                //获取企业数据
                BigDecimal qyLoss = BigDecimal.ZERO;
                EnterpriseDirectEconomy enterpriseDirectEconomyData = enterpriseDirectEconomyRepository.getEnterpriseDirectEconomyData(xsemId, province, city, county, XczhConstants.ZONING_LOSS);
                if (!PlatformObjectUtils.isEmpty(enterpriseDirectEconomyData)) {
                    qyLoss = enterpriseDirectEconomyData.getLoss();
                }
                economicLossesSummary.setEnterprise(qyLoss);
                //合计相关计算
                total = total.add(qyLoss);
                //小计
                qySubtotal = qySubtotal.add(qyLoss);

                //水利
                BigDecimal slLoss = BigDecimal.ZERO;
                ParamsVo paramsVo = new ParamsVo();
                paramsVo.setXsemId(xsemId);
                paramsVo.setReportType(XczhConstants.WATER_SYS_LOSS_EQUIPMENT);
                paramsVo.setProvince(province);
                paramsVo.setCity(city);
                paramsVo.setCounty(county);
                slLoss = losRepEscalationRepository.getTotalLoss(paramsVo);
                if (PlatformObjectUtils.isEmpty(slLoss)) {
                    slLoss = BigDecimal.ZERO;
                }
                economicLossesSummary.setWaterConservancy(slLoss);
                //合计相关计算
                total = total.add(slLoss);
                //小计
                slSubtotal = slSubtotal.add(slLoss);

                //文物古建
                BigDecimal wwgjLoss = new BigDecimal("0.0");
                List<ResultVo> wwgjList = new ArrayList<>();
                List<ResultVo> architectureTotal = relicsHistoricSitesRepository.getArchitectureTotalLoss(xsemId, province, city, county, XczhConstants.RELICS_HISTORIC_SITES);
                List<ResultVo> currentAssetsTotal = relicsHistoricSitesRepository.getCurrentAssetsTotalLoss(xsemId, province, city, county, XczhConstants.RELICS_HISTORIC_SITES);
                wwgjList.addAll(architectureTotal);
                wwgjList.addAll(currentAssetsTotal);
                for (ResultVo item : wwgjList) {
                    wwgjLoss = wwgjLoss.add(item.getLoss() != null ? new BigDecimal(item.getLoss()) : BigDecimal.ZERO);
                }

                wwgjLoss.add(wwgjLoss);
                economicLossesSummary.setCulturalHeritage(wwgjLoss);
                //合计相关计算
                total = total.add(wwgjLoss);
                //小计
                wwgjSubtotal = wwgjSubtotal.add(wwgjLoss);

                //其他
                BigDecimal qtLoss = new BigDecimal("0.0");
                ParamsVo paramsVo2 = new ParamsVo();
                paramsVo2.setXsemId(xsemId);
                paramsVo2.setReportType(XczhConstants.OTHER_LOSS);
                paramsVo2.setProvince(province);
                paramsVo2.setCity(city);
                paramsVo2.setCounty(county);
                List<ResultVo> qtList = OtherLossRepository.getTotalLoss(paramsVo2);
                for (ResultVo item : qtList) {
                    qtLoss = qtLoss.add(item.getLoss() != null ? new BigDecimal(item.getLoss()).divide(new BigDecimal("10000")) : BigDecimal.ZERO);
                }
                economicLossesSummary.setOther(qtLoss);
                //合计相关计算
                total = total.add(qtLoss);
                //小计
                qtSubtotal = qtSubtotal.add(qtLoss);

                //室内外财产
                BigDecimal snLoss = new BigDecimal("0.0");
                BigDecimal swLoss = new BigDecimal("0.0");
                IndoorOutdoorPropertyLosses indoorOutdoorPropertyLosses = enterpriseDirectEconomyRepository.getIndoorOutdoorPropertyLossesByXsemIdAndCounty(xsemId, province, city, county);
                if (!PlatformObjectUtils.isEmpty(indoorOutdoorPropertyLosses)) {
                    snLoss = indoorOutdoorPropertyLosses.getIndoorLoss();
                    swLoss = indoorOutdoorPropertyLosses.getOutdoorLoss();
                }
                economicLossesSummary.setIndoorProperty(snLoss);
                economicLossesSummary.setOutdoorProperty(swLoss);
                //小计
                snSubtotal = snSubtotal.add(snLoss);
                swSubtotal = swSubtotal.add(swLoss);
                //合计相关计算
                total = total.add(snLoss).add(swLoss);
                //小计的合计
                totalSubtotal = totalSubtotal.add(total);
                economicLossesSummary.setTotal(total);
                economicLossesSummary.setDelFlag("0");
                economicLossesSummary.setCreateUser(PlatformSessionContext.getUserID());
                economicLossesSummary.setCreateTime(new Date());
                enterpriseDirectEconomyRepository.saveEconomicLossesSummary(economicLossesSummary);
            }
        }
    }

    @Override
    public List<EconomicLossesSummary> getEconomicLossesSummaryData(String xsemId) {
        EarEveManage earEveManage = earEveManageService.findById(xsemId);
        List<EconomicLossesSummary> economicLossesSummaryData = enterpriseDirectEconomyRepository.getEconomicLossesSummaryData(xsemId);
        if(economicLossesSummaryData.size()>0){
            //房屋小计
            BigDecimal ruralHouseSubtotal = BigDecimal.ZERO;
            BigDecimal ruralSharedSubtotal = BigDecimal.ZERO;
            BigDecimal cityHouseSubtotal = BigDecimal.ZERO;
            BigDecimal citySharedSubtotal = BigDecimal.ZERO;
            BigDecimal governmentOfficeSubtotal = BigDecimal.ZERO;
            BigDecimal educationSystemSubtotal = BigDecimal.ZERO;//教育系统
            BigDecimal healthSystemSubtotal = BigDecimal.ZERO;//医疗系统
            BigDecimal otherUsageSubtotal = BigDecimal.ZERO;//其他用途

            //生命线小计
            BigDecimal dlSubtotal = BigDecimal.ZERO;
            BigDecimal gpsSubtotal = BigDecimal.ZERO;
            BigDecimal gqSubtotal = BigDecimal.ZERO;
            BigDecimal grSubtotal = BigDecimal.ZERO;
            BigDecimal jtSubtotal = BigDecimal.ZERO;
            BigDecimal csyqgSubtotal = BigDecimal.ZERO;
            BigDecimal txSubtotal = BigDecimal.ZERO;
            BigDecimal gbdsSubtotal = BigDecimal.ZERO;
            BigDecimal szssSubtotal = BigDecimal.ZERO;
            BigDecimal tlSubtotal = BigDecimal.ZERO;
            //企业小计
            BigDecimal qySubtotal = BigDecimal.ZERO;
            //水利小计
            BigDecimal slSubtotal = BigDecimal.ZERO;
            //文物古建小计
            BigDecimal wwgjSubtotal = BigDecimal.ZERO;
            //其他小计
            BigDecimal qtSubtotal = BigDecimal.ZERO;
            //室内外财产小计
            BigDecimal snSubtotal = BigDecimal.ZERO;
            //室外财产小计
            BigDecimal swSubtotal = BigDecimal.ZERO;
            //合计小计
            BigDecimal totalSubtotal = BigDecimal.ZERO;
            for(EconomicLossesSummary item:economicLossesSummaryData){
                //房屋小计
                ruralHouseSubtotal=ruralHouseSubtotal.add(null == item.getRuralResidential()?BigDecimal.ZERO:item.getRuralResidential());
                ruralSharedSubtotal=ruralSharedSubtotal.add(null == item.getRuralPublic()?BigDecimal.ZERO:item.getRuralPublic());
                cityHouseSubtotal=cityHouseSubtotal.add(null == item.getUrbanResidential()?BigDecimal.ZERO:item.getUrbanResidential());
                citySharedSubtotal=citySharedSubtotal.add(null == item.getUrbanPublic()?BigDecimal.ZERO:item.getUrbanPublic());
                governmentOfficeSubtotal=governmentOfficeSubtotal.add(null == item.getGovernmentOffice()?BigDecimal.ZERO:item.getGovernmentOffice());
                educationSystemSubtotal=educationSystemSubtotal.add(null == item.getEducationSystem()?BigDecimal.ZERO:item.getEducationSystem());
                healthSystemSubtotal=healthSystemSubtotal.add(null == item.getHealthcareSystem()?BigDecimal.ZERO:item.getHealthcareSystem());
                otherUsageSubtotal=otherUsageSubtotal.add(null == item.getOtherUsage()?BigDecimal.ZERO:item.getOtherUsage());
                //生命线小计
                dlSubtotal=dlSubtotal.add(null == item.getElectricity()?BigDecimal.ZERO:item.getElectricity());
                gpsSubtotal =gpsSubtotal .add(null == item.getWaterSupplyAndDrainage()?BigDecimal.ZERO:item.getWaterSupplyAndDrainage());
                gqSubtotal =gqSubtotal .add(null == item.getGasSupply()?BigDecimal.ZERO:item.getGasSupply());
                grSubtotal =grSubtotal .add(null == item.getHeatingSupply()?BigDecimal.ZERO:item.getHeatingSupply());
                jtSubtotal =jtSubtotal .add(null == item.getTraffic()?BigDecimal.ZERO:item.getTraffic());
                csyqgSubtotal =csyqgSubtotal .add(null == item.getOilAndGasPipelines()?BigDecimal.ZERO:item.getOilAndGasPipelines());
                txSubtotal =txSubtotal .add(null == item.getCommunication()?BigDecimal.ZERO:item.getCommunication());
                gbdsSubtotal =gbdsSubtotal .add(null == item.getBroadcastingAndTelevision()?BigDecimal.ZERO:item.getBroadcastingAndTelevision());
                szssSubtotal =szssSubtotal .add(null == item.getMunicipalFacilities()?BigDecimal.ZERO:item.getMunicipalFacilities());
                tlSubtotal =tlSubtotal .add(null == item.getRailway()?BigDecimal.ZERO:item.getRailway());
                //企业小计
                qySubtotal =qySubtotal .add(null == item.getEnterprise()?BigDecimal.ZERO:item.getEnterprise());
                //水利小计
                slSubtotal =slSubtotal .add(null == item.getWaterConservancy()?BigDecimal.ZERO:item.getWaterConservancy());
                //文物古建小计
                wwgjSubtotal =wwgjSubtotal .add(null == item.getCulturalHeritage()?BigDecimal.ZERO:item.getCulturalHeritage());
                //其他小计
                qtSubtotal =qtSubtotal .add(null == item.getOther()?BigDecimal.ZERO:item.getOther());
                //室内外财产小计
                snSubtotal =snSubtotal .add(null == item.getIndoorProperty()?BigDecimal.ZERO:item.getIndoorProperty());
                //室外财产小计
                swSubtotal =swSubtotal .add(null == item.getOutdoorProperty()?BigDecimal.ZERO:item.getOutdoorProperty());
                //合计小计
                totalSubtotal =totalSubtotal .add(null == item.getTotal()?BigDecimal.ZERO:item.getTotal());
            }
            //小计
            EconomicLossesSummary entity = new EconomicLossesSummary();
            entity.setId(UUIDGenerator.getUUID());
            entity.setXsemId(xsemId);
            entity.setEventName(earEveManage.getEventName());
            entity.setEventTime(earEveManage.getEventTime());
            entity.setProvince("小计");
            entity.setRuralResidential(ruralHouseSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setRuralPublic(ruralSharedSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setUrbanResidential(cityHouseSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setUrbanPublic(citySharedSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setGovernmentOffice(governmentOfficeSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setEducationSystem(educationSystemSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setHealthcareSystem(healthSystemSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setOtherUsage(otherUsageSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setElectricity(dlSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setWaterSupplyAndDrainage(gpsSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setGasSupply(gqSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setHeatingSupply(grSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setTraffic(jtSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setOilAndGasPipelines(csyqgSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setCommunication(txSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setBroadcastingAndTelevision(gbdsSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setMunicipalFacilities(szssSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setRailway(tlSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));

            entity.setEnterprise(qySubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setWaterConservancy(slSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setCulturalHeritage(wwgjSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setOther(qtSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setIndoorProperty(snSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setOutdoorProperty(swSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setTotal(totalSubtotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            entity.setDelFlag("0");
            entity.setCreateUser(PlatformSessionContext.getUserID());
            entity.setCreateTime(new Date());
            economicLossesSummaryData.add(entity);


            //分项合计
            //房屋分项合计
            BigDecimal fwTotal = ruralHouseSubtotal.add(ruralSharedSubtotal).add(cityHouseSubtotal).add(citySharedSubtotal).add(governmentOfficeSubtotal).add(educationSystemSubtotal).add(healthSystemSubtotal).add(otherUsageSubtotal);
            //生命线分项合计
            BigDecimal smxTotal = dlSubtotal.add(gpsSubtotal).add(gqSubtotal).add(grSubtotal).add(jtSubtotal).add(csyqgSubtotal).add(txSubtotal).add(gbdsSubtotal).add(szssSubtotal).add(tlSubtotal);
            //室内外财产分项合计
            BigDecimal snwTotal = snSubtotal.add(swSubtotal);
            EconomicLossesSummary economicLossesSummary = new EconomicLossesSummary();
            economicLossesSummary.setId(UUIDGenerator.getUUID());
            economicLossesSummary.setXsemId(xsemId);
            economicLossesSummary.setEventName(earEveManage.getEventName());
            economicLossesSummary.setEventTime(earEveManage.getEventTime());
            economicLossesSummary.setProvince("分项合计");
            economicLossesSummary.setRuralResidential(fwTotal.setScale(2,   BigDecimal.ROUND_HALF_UP));//房屋分项合计
            economicLossesSummary.setElectricity(smxTotal.setScale(2,   BigDecimal.ROUND_HALF_UP));//生命线分项合计
            economicLossesSummary.setEnterprise(qySubtotal);
            economicLossesSummary.setWaterConservancy(slSubtotal);
            economicLossesSummary.setCulturalHeritage(wwgjSubtotal);
            economicLossesSummary.setOther(qtSubtotal);
            economicLossesSummary.setIndoorProperty(snwTotal.setScale(2,   BigDecimal.ROUND_HALF_UP));
            economicLossesSummary.setTotal(totalSubtotal);
            economicLossesSummary.setDelFlag("0");
            economicLossesSummary.setCreateUser(PlatformSessionContext.getUserID());
            economicLossesSummary.setCreateTime(new Date());
            economicLossesSummaryData.add(economicLossesSummary);
            //百分比
            //房屋百分比
            BigDecimal fwPercentage = fwTotal.divide(totalSubtotal, 4, RoundingMode.HALF_UP);
            //生命线百分比
            BigDecimal smxPercentage = smxTotal.divide(totalSubtotal, 4, RoundingMode.HALF_UP);
            EconomicLossesSummary economicLossesSummary2 = new EconomicLossesSummary();
            economicLossesSummary2.setId(UUIDGenerator.getUUID());
            economicLossesSummary2.setXsemId(xsemId);
            economicLossesSummary2.setEventName(earEveManage.getEventName());
            economicLossesSummary2.setEventTime(earEveManage.getEventTime());
            economicLossesSummary2.setProvince("百分比");
            economicLossesSummary2.setRuralResidential(fwPercentage);//房屋百分比
            economicLossesSummary2.setElectricity(smxPercentage);//生命线百分比
            economicLossesSummary2.setEnterprise(qySubtotal.divide(totalSubtotal, 4, RoundingMode.HALF_UP));
            economicLossesSummary2.setWaterConservancy(slSubtotal.divide(totalSubtotal, 4, RoundingMode.HALF_UP));
            economicLossesSummary2.setCulturalHeritage(wwgjSubtotal.divide(totalSubtotal, 4, RoundingMode.HALF_UP));
            economicLossesSummary2.setOther(qtSubtotal.divide(totalSubtotal, 4, RoundingMode.HALF_UP));
            economicLossesSummary2.setIndoorProperty(snwTotal.divide(totalSubtotal, 4, RoundingMode.HALF_UP));
            economicLossesSummary2.setDelFlag("0");
            economicLossesSummary2.setCreateUser(PlatformSessionContext.getUserID());
            economicLossesSummary2.setCreateTime(new Date());
            economicLossesSummary2.setTotal(new BigDecimal("1"));

            economicLossesSummaryData.add(economicLossesSummary2);

        }
        return economicLossesSummaryData;
    }

    @Override
    public List<IndoorOutdoorPropertyLosses> getIndoorOutdoorPropertyLossesData(String xsemId, String type) {
        return enterpriseDirectEconomyRepository.getIndoorOutdoorPropertyLossesByXsemId(xsemId,type);
    }


    //四舍五入      ResettlementPopulationEvaluation
    private BigDecimal percentage(BigDecimal a, BigDecimal b){
        BigDecimal bigDecimal = a.multiply(b).setScale(2, BigDecimal.ROUND_HALF_UP);
       /* BigDecimal rateStr = new BigDecimal(a * b).setScale(2, BigDecimal.ROUND_HALF_UP);
        DecimalFormat decimalFormat = new DecimalFormat("0.00#");*/
        //String format = String.format("%.2f", rateStr);
        //return format+"%";
        return bigDecimal;
    }
    private float division(String a, String b){
        if(PlatformObjectUtils.isEmpty(a) || PlatformObjectUtils.isEmpty(b)){
            return 0;
        }
        Float aFloat = Float.valueOf(a);
        Float bFloat = Float.valueOf(b);
        if(aFloat ==0 || bFloat==0 || aFloat ==0.0 || bFloat==0.0){
            return 0;
        }
        double rateStr = new BigDecimal(aFloat / bFloat).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        DecimalFormat decimalFormat = new DecimalFormat("0.00#");
        return Float.parseFloat(decimalFormat.format(rateStr));
    }

    private  List<PersonnelInjuryAssessment> startPage(List<PersonnelInjuryAssessment> list, Integer pageNum, Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List<PersonnelInjuryAssessment> pageList = list.subList(fromIndex, toIndex);
        return pageList;
    }

    private  List<LifelineSystemLoss> lifelineSystemLossPage(List<LifelineSystemLoss> list, Integer pageNum, Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List<LifelineSystemLoss> pageList = list.subList(fromIndex, toIndex);
        return pageList;
    }

}
